package org.lim.infrastructure.interception;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.lim.infrastructure.content.BaseContext;
import org.lim.infrastructure.properties.JwtProperties;
import org.lim.infrastructure.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
@Slf4j
public class JwtInterception implements HandlerInterceptor {
//    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String uri = request.getRequestURI();
//        if (uri.contains("/api/doc.html") ||uri.contains("/api/user/login")||uri.contains("/api/user/register")||uri.contains("/api/user/logout")|| uri.contains("/api/webjars/") || uri.contains("/api/v2/api-docs") || uri.contains("/api/swagger-resources")) {
//            return true;
//        }
        String requestURI = request.getRequestURI();
        log.info("拦截路径: {}", requestURI); // 打印请求路径
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
//        if (!(handler instanceof HandlerMethod)) {
//            //当前拦截到的不是动态方法，直接放行
//            return true;
//        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getEmpToken());

        //2、校验令牌
        try {
//            log.info("jwt校验:{}", token);
            Claims claims = JwtUtils.parseJwt(token,jwtProperties.getSecretKey());
            Long userId = Long.valueOf(claims.get("id").toString());
//            log.info("当前员工id：", userId);
            BaseContext.setCurrentId(userId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
    //资源响应给客户端后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完之后，清理
        BaseContext.removeCurrentId();
    }

}
